package cn.bdqn.realm;

import cn.bdqn.model.ConstUtil;
import cn.bdqn.sys.mapper.EnterpriseMapper;
import cn.bdqn.sys.mapper.UserMapper;
import cn.bdqn.sys.model.User;
import cn.bdqn.sys.model.UserExample;
import cn.bdqn.sys.vomapper.ResourcesVoMapper;
import cn.bdqn.util.ShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionManager;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author gurilla
 * @create 2019-08-17 11:18
 */
@Component
public class UserRealm extends AuthorizingRealm {
    @Resource
    private UserMapper userMapper;

    @Resource
    private EnterpriseMapper enterpriseMapper;

    @Resource
    private ResourcesVoMapper resourcesVoMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        User user= (User) principals.getPrimaryPrincipal();
        Integer userid = user.getUid ();
        List<String> permsList= resourcesVoMapper.getPerms(userid);
        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for(String perms : permsList){
            if(StringUtils.isEmpty( perms )){
                continue;
            }
            permsSet.addAll( Arrays.asList(perms.trim().split(",")));
        }

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String account = ((UsernamePasswordToken) token).getUsername();
        UserExample example = new UserExample();
        example.createCriteria().andAccountEqualTo(account);
        User user = userMapper.selectByExample(example).get(0);

        if(user==null){
            throw new UnknownAccountException("帐号或密码不正确");
        }
        DefaultWebSecurityManager securityManager=(DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
        DefaultSessionManager sessionManager=(DefaultSessionManager) securityManager.getSessionManager();
        Collection<Session> sessions=sessionManager.getSessionDAO().getActiveSessions();
        //获取当前已登陆的用户的session列表
        for(Session session:sessions){
            //清除该用户以前登录时保存的session
            User u=null;
            try {
                u= (User) session.getAttribute(ConstUtil.USER);
            }catch (Exception e){
                continue;
            }
            if(u==null||StringUtils.isEmpty( u.getAccount( ))){
                continue;
            }
            if(account.equalsIgnoreCase(u.getAccount())) {
                sessionManager.getSessionDAO().delete(session);
            }
        }
        ShiroUtils.setSessionAttribute(ConstUtil.USER,user );
        ShiroUtils.setSessionAttribute(ConstUtil.ENTERPRISE,enterpriseMapper.selectByPrimaryKey(user.getEid()) );
        return new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getAccount()), getName());
    }

    @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        HashedCredentialsMatcher shaCredentialsMatcher = new HashedCredentialsMatcher();
        shaCredentialsMatcher.setHashAlgorithmName(ShiroUtils.hashAlgorithmName);
        shaCredentialsMatcher.setHashIterations(ShiroUtils.hashIterations);
        super.setCredentialsMatcher(shaCredentialsMatcher);
    }
}
